<?php
/**
 * Add to a Mission
 * Display a popup to look through existing mission
 * and a the contact to the mission
 * 
 * @author Xavier VILAIN
 * @package contact
 */

/* @var $contact Hive\Ressource */
use Hive\Mission\Partner;
use Hive\Mission;

$xview = Xview::instance();
$contact = $xview->component('ressource', 'object');
$rid = $contact->getId();
$missionIds = $xview->val('codes');
if(is_array($missionIds) && !empty($rid))
{
	$role = Partner::ROLE_CANDIDATE;
	foreach($missionIds as $missionid)
	{
		if(empty($missionid))
		{
			continue;
		}
		try {
			/* @var $mission Hive\Mission */
			$mission = Fox\Dao::load(Mission::className(), $missionid);
			$partner = $mission->findPartners($missionid.':'.$role.':'.$rid);
			if($partner->exists()) {
				
			} else {
				$partner = new Partner();
				$partner->setFields(array('missionid'=> $missionid,
										 'partnerid' => $rid,
										'role' => $role,
										'status' => Partner::STATUS_DEFAULT));
				$partner->create();
				Fox\Message::Success(Msg(Hive::BUNDLE,Hive::MSG_MISSION_HAS_BEEN_ASSIGNED,$contact->name(),$mission->label()));
			}
		}	
		catch(Fox\Object\Exception\Save $e)
		{
			Fox\Core\Errors::pushMessage($e);
		}
		catch(Fox\Object\Exception\NotExist $e)
		{
			Fox\Core\Errors::pushMessage($e);
		}
	}
}
return $xview->messages(true);